package com.jianjian.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jianjian.constant.RedisConstant;
import com.jianjian.dao.SetmealDao;
import com.jianjian.entity.PageResult;

import com.jianjian.pojo.CheckItem;
import com.jianjian.pojo.Setmeal;
import com.jianjian.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;


import java.util.HashMap;

import java.util.Map;

/**
 * @author Zsir
 * @create 2022-02-09 19:24
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    //注入JedisPool操作Redis
    @Autowired
    private JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {

        setmealDao.add(setmeal);
    //将图片名称保存到Redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);
    if (checkgroupIds !=null && checkgroupIds.length>0){
            //绑定套餐和检查组的多对多关系
            SetSetmealBCheckgroupIds(setmeal.getId(),checkgroupIds);
        }


    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {

        if (queryString!=null && queryString.length()>0) {
            PageHelper.startPage(1, pageSize);
        }else {
            PageHelper.startPage(currentPage,pageSize);
        }
        Page<CheckItem> page = setmealDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }


    //设置套餐和检查组多对多关系，操作t_setmeal_checkgroup
    public void SetSetmealBCheckgroupIds(Integer id ,Integer[] checkgroupIds){
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmealId", id);
            map.put("checkgroupId", checkgroupId);

            setmealDao.SetSetmealBCheckgroupIds(map);
        }
    }

}
